package com.zsck.pos.net;


import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

import com.zsck.net.Utils.BaseObserver;
import com.zsck.pos.activity.LoginActivity;
import com.zsck.pos.activity.MainActivity;
import com.zsck.pos.bean.LoginResult;
import com.zsck.pos.utils.LogUtil;
import com.zsck.pos.utils.SharePreferenceUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;

import static com.zsck.net.Utils.RxHelper.observableIO2Main;

/**
 * Observer加入加载框
 *
 * @param <T>
 */
public abstract class MyObserver<T> extends BaseObserver<T> {
    private boolean mShowDialog;
    private ProgressDialog dialog;
    private Context mContext;
    private Disposable d;

    public MyObserver(Context context, Boolean showDialog) {
        mContext = context;
        mShowDialog = showDialog;
    }

    public MyObserver(Context context) {
        this(context, true);
    }

    @Override
    public void onSubscribe(Disposable d) {
        this.d = d;
        if (!isConnected(mContext)) {
            Toast.makeText(mContext, "未连接网络", Toast.LENGTH_SHORT).show();
            if (d.isDisposed()) {
                d.dispose();
            }
        } else {
            if (dialog == null && mShowDialog == true) {
                dialog = new ProgressDialog(mContext);
                dialog.setMessage("正在加载中");
                dialog.show();
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        if (d.isDisposed()) {
            d.dispose();
        }
        hidDialog();
        super.onError(e);
    }

    @Override
    public void onComplete() {
        if (d.isDisposed()) {
            d.dispose();
        }
        hidDialog();
        super.onComplete();
    }


    public void hidDialog() {
        if (dialog != null && mShowDialog == true)
            dialog.dismiss();
        dialog = null;
    }

    /**
     * 是否有网络连接，不管是wifi还是数据流量
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null) {
            return false;
        }
        boolean available = info.isAvailable();
        return available;
    }

    /**
     * 取消订阅
     */
    public void cancleRequest() {
        if (d != null && d.isDisposed()) {
            d.dispose();
            hidDialog();
        }
    }



    public void notLoggedIn(){
        login();
    }




    private void login(){
        String mUsername = SharePreferenceUtils.getString(mContext,"username");
        String mPassword = SharePreferenceUtils.getString(mContext,"password");


        Map<String,String> map = new HashMap<>();
        map.put("accountId",mUsername);
        map.put("password",mPassword);
        MyObserver<LoginResult> observer = new MyObserver<LoginResult>(mContext) {
            @Override
            public void onSuccess(LoginResult result) {
                onLogin(result);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test",e.getMessage());
                Toast.makeText(mContext,errorMsg,Toast.LENGTH_SHORT).show();
                NetConfig.userInfo = null;
                Intent intent = new Intent();
                ComponentName componentName= new ComponentName("com.ums.sz.os","com.zsck.pos.activity.LoginActivity");
                intent.setComponent(componentName);
                mContext.startActivity(intent);
            }

            @Override
            public void reRequest() {
                login();
            }
        };
        RetrofitCilent.getApiService().login(map).
                compose(observableIO2Main(mContext)).subscribe(observer);
    }

    private void onLogin(LoginResult result){
        if(result == null){
            LogUtil.i("MyObserver","登录错误");
            NetConfig.userInfo = null;
            Intent intent = new Intent();
            ComponentName componentName= new ComponentName("com.ums.sz.os","com.zsck.pos.activity.LoginActivity");
            intent.setComponent(componentName);
            mContext.startActivity(intent);
            return;
        }
        if(!result.isState() || result.getData() == null){
            Toast.makeText(mContext, result.getMessage(),Toast.LENGTH_SHORT).show();
            NetConfig.userInfo = null;
            Intent intent = new Intent();
            ComponentName componentName= new ComponentName("com.ums.sz.os","com.zsck.pos.activity.LoginActivity");
            intent.setComponent(componentName);
            mContext.startActivity(intent);
            return;
        }
        NetConfig.userInfo = result.getData();
        SharePreferenceUtils.putString(mContext, "accessToken", NetConfig.userInfo.getAccessToken());
        SharePreferenceUtils.putString(mContext, "accountId", NetConfig.userInfo.getAccountId());
        SharePreferenceUtils.putString(mContext, "name", NetConfig.userInfo.getName());
        reRequest();
    }



}

